package com.frogs.ucenter.service.daoimpl.aop;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.frogs.component.permission.api.service.PermissionHelper;
import com.frogs.component.permission.entity.User;
import com.frogs.system.util.ChangeTypeEnum;
import com.frogs.system.util.UserRechargeableCardStatusEnum;
import com.frogs.ucenter.dao.UserRechargeableCardDao;
import com.frogs.ucenter.dao.UserRechargeableCardLogDao;
import com.frogs.ucenter.entity.UserRechargeableCard;
import com.frogs.ucenter.entity.UserRechargeableCardLog;

@Aspect
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service("userRechargeableCardLogAopImpl")
public class UserRechargeableCardLogAopImpl {
	@Resource
	private UserRechargeableCardLogDao userRechargeableCardLogDao;
	@Resource
	private UserRechargeableCardDao userRechargeableCardDao;
	@Resource(name = "permissionHelper")
	private PermissionHelper permissionHelper;
	
	private static final Logger log = LoggerFactory.getLogger(UserRechargeableCardLogAopImpl.class);

	
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.controller.UserRechargeableCardController.uploadUserRechargeableCard(..)) || "
			+ "execution(* com.frogs.ucenter.controller.UserRechargeableCardController.updateUserRechargeableCard(..)) || "
			+ "execution(* com.frogs.ucenter.controller.UserRechargeableCardController.deleteUserRechargeableCard(..))")
	public void doAfterReturning(JoinPoint jp)
	{
		try {
			HttpServletRequest req = (HttpServletRequest)jp.getArgs()[0];//切入点方法入参
			boolean flag = (Boolean) req.getAttribute("flag");
			String method = jp.getStaticPart().getSignature().getName();
			if(!flag){
				return;
			}
			UserRechargeableCard userRechargeableCard = new UserRechargeableCard();
			int changeType = 0;
			User user = permissionHelper.getUser();
			int userId = user.getUserId();
			if(method.equals("uploadUserRechargeableCard")){
				List<UserRechargeableCard> userRechargeableCardList = (List<UserRechargeableCard>)req.getAttribute("cardList");
				changeType = ChangeTypeEnum.ADD.getId();
				batchInsertLog(userRechargeableCardList, changeType, userId);
			}else if(method.equals("updateUserRechargeableCard")){
				//说明：由于更新是sql执行的，这里的日志不能判断是否真的有更新到，所以全部记录更新的状态（指的是执行状态，并不是充值卡的实际状态）。
				String deleteId = jp.getArgs()[4].toString();
				String[] arr = deleteId.split(",");
				changeType = ChangeTypeEnum.UPDATE.getId();
				int bandType = Integer.parseInt(req.getAttribute("bandType").toString());//1-绑定，2-解绑
				int status = 0;//充值卡状态
				if(bandType == 1){
					status = UserRechargeableCardStatusEnum.USE.getId();
				}else if(bandType == 2){
					status = UserRechargeableCardStatusEnum.UNUSED.getId();
				}else{
					return;
				}
				for(int i=0;i<arr.length;i++){
					userRechargeableCard = new UserRechargeableCard();
					userRechargeableCard.setId(Integer.parseInt(arr[i]));
					userRechargeableCard.setStatus(status);
					insertLog(userRechargeableCard, changeType, userId);
				}
			}
		} catch (Exception e) {
			log.error("func[doAfterReturning] jp[" + jp + "] error[" + e.getMessage() + "]", e);
		}
		
	}
	
	@Async
	private void insertLog(UserRechargeableCard userRechargeableCard, int changeType, int creater){
		UserRechargeableCardLog userRechargeableCardLog = new UserRechargeableCardLog();
		userRechargeableCardLog.setChangeType(changeType);
		userRechargeableCardLog.setCreater(creater);
		userRechargeableCardLog.setOldId(userRechargeableCard.getId());
		userRechargeableCardLog.setUpdateTime(new Date());
		userRechargeableCardLog.setStatus(userRechargeableCard.getStatus());
		userRechargeableCardLogDao.insert(userRechargeableCardLog);
	}
	@Async
	private void batchInsertLog(List<UserRechargeableCard> userRechargeableCardList, int changeType, int creater){
		List<UserRechargeableCardLog> cardListLog = new ArrayList<UserRechargeableCardLog>();
		for(int i=0;i<userRechargeableCardList.size();i++){
			UserRechargeableCardLog userRechargeableCardLog = new UserRechargeableCardLog();
			userRechargeableCardLog.setChangeType(changeType);
			userRechargeableCardLog.setCreater(creater);
			userRechargeableCardLog.setUpdateTime(new Date());
			userRechargeableCardLog.setDenomination(userRechargeableCardList.get(i).getDenomination());
			userRechargeableCardLog.setCreateTime(new Date());
			userRechargeableCardLog.setOldId(userRechargeableCardList.get(i).getId());
			userRechargeableCardLog.setRechargeCard(userRechargeableCardList.get(i).getRechargeCard());
			userRechargeableCardLog.setCardPasswd(userRechargeableCardList.get(i).getCardPasswd());
			userRechargeableCardLog.setStatus(userRechargeableCardList.get(i).getStatus());
			cardListLog.add(userRechargeableCardLog);
		}
		userRechargeableCardLogDao.batchInsert(cardListLog);
	}
}
